﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SoundEdge.Media.Wave;
using SoundEdge.Media.Settings;

namespace SoundEdge.WinControls.Settings
{
    public partial class AsioOutSettingsPanel : UserControl
    {
        private AsioOutSettings _settings;

        public AsioOutSettingsPanel(AsioOutSettings settings)
        {
            _settings = settings;
            InitializeComponent();
            InitialiseAsioControls();
        }

        private void InitialiseAsioControls()
        {
            // Just fill the comboBox AsioDriver with available driver names
            var asioDriverNames = AsioOut.GetDriverNames();
            foreach (string driverName in asioDriverNames)
            {
                comboBoxAsioDriver.Items.Add(driverName);
            }

            string selected = null;
            if (_settings != null)
            {
                selected = comboBoxAsioDriver.Items.OfType<string>().FirstOrDefault(item => item == _settings.DriverName);
            }

            comboBoxAsioDriver.SelectedIndex = string.IsNullOrEmpty(selected) ? 0 : comboBoxAsioDriver.Items.IndexOf(selected);
        }

        public string SelectedDeviceName { get { return (string)comboBoxAsioDriver.SelectedItem; } }

        private void buttonControlPanel_Click(object sender, EventArgs args)
        {
            try
            {
                using (var asio = new AsioOut(SelectedDeviceName))
                {
                    asio.ShowControlPanel();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void comboBoxAsioDriver_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_settings == null)
            {
                return;
            }
            _settings.DriverName = SelectedDeviceName;
        }
    }
}
